package com.atguigu.daijia.common.service;


import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     *
     * @param exchange
     * @param routingKey
     * @param message
     * @return
     */
    public boolean sendMessage(String exchange,
                               String routingKey,
                               Object message) {
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
        return true;
    }

    public void sendDelayMessage(String exchangeProfitsharing,
                                 String routingProfitsharing,
                                 String toJSONString,
                                 int profitsharingDelayTime) {
        // 使用RabbitTemplate发送消息
        rabbitTemplate.convertAndSend(exchangeProfitsharing, routingProfitsharing, toJSONString, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置消息的延迟时间（单位：毫秒）
                long delayTime = profitsharingDelayTime * 1000L; // 将秒转换为毫秒
                message.getMessageProperties().setHeader("x-delay", delayTime);
                return message;
            }
        });
    }

}
